import { useState } from "react";
import { connect, Link, history } from 'umi';
import { Skeleton, PageHeader, Descriptions, message, Select, Space, Input, Tooltip, Tabs, Modal } from 'antd';
import { ClockCircleOutlined } from '@ant-design/icons'
import styles from './style.less';
import { useEffect } from "react";
import { TaskStatus } from '../../ProjectTask/TaskPage'
import RichText, { RichTextEdit } from '@/components/RichText'
import EditAble from '@/components/EditAble';
import ArrayUtils from '@/utils/ArrayUtils';
import { PROJECT_TASK_STATUS, COST_TIME_UNIT, TASK_TYPE } from '@/consts/project'
import { formetDate, formetTime, checkRangeDateNotNull } from '@/utils/dateUtils'
import UserBrief from '@/components/UserBrief';
import NumberInput from '@/components/Input/NumberInput';
import { getDetail, update, deleteTask, updateIsArchived } from '@/services/project/task';
import TextButton from '@/components/TextButton'
import ProjectProdSelect from '@/pages/projects/components/ProjectProduct/ProjectProdSelect'
import ProjectDevSelect from '@/pages/projects/components/ProjectDev/ProjectDevSelect'
import ProjectQaSelect from '@/pages/projects/components/ProjectQA/ProjectQaSelect'
import ProjectItemLog from '@/pages/projects/components/ProjectItemLog'
import ProjectComment from '@/pages/projects/components/ProjectComment'
import ActionDropdown from '@/components/ActionDropdown';
import ProjectItemLink from '@/pages/projects/components/ProjectItemLink'
import moment from 'moment';

const { Option } = Select;
const { TabPane } = Tabs;


const TaskRelItemTypeSelect = (props) => {
    const {
        defaultItemType,
        defaultItemId,
        projectId,
        allowClear,
        onSelect,
        onChange,
        width
    } = props;

    useEffect(() => {
        setProjectItemSelectData({
            projectId,
            value: defaultItemId,
            type: defaultItemType
        })
    }, [])

    const [projectItemSelectData, setProjectItemSelectData] = useState({})

    const onItemSelect = (id, item) => {
        if (onSelect) {
            onSelect({
                projectItemType: projectItemSelectData.type,
                projectItemId: id,
                projectItem: item
            })
        }
    }

    const onItemChange = (value) => {
        if (onChange) {
            onChange({
                projectItemType: projectItemSelectData.type,
                projectItemId: value,
            })
        }
    }

    return (<Input.Group
        style={{ display: "flex", width: "100%" }}
        compact>
        <Select
            style={{ width: "80px" }}
            value={projectItemSelectData.type}
            onSelect={(value) => {
                setProjectItemSelectData({
                    projectId,
                    type: value
                })
            }} placeholder={"请输入任务类型"}>
            {ArrayUtils.jsonToArray(TASK_TYPE).map(item => <Option value={`${item.key}`} key={`${item.key}`}>{item.value.name}</Option>)}
        </Select>
        {projectItemSelectData.type === "PROD" &&
            <ProjectProdSelect {...projectItemSelectData} allowClear={allowClear} width={width} onSelect={onItemSelect} onChange={onItemChange} />
        }
        {projectItemSelectData.type === "DEV" &&
            <ProjectDevSelect {...projectItemSelectData} allowClear={allowClear} width={width} onSelect={onItemSelect} onChange={onItemChange} />
        }
        {projectItemSelectData.type === "QA" &&
            <ProjectQaSelect {...projectItemSelectData} allowClear={allowClear} width={width} onSelect={onItemSelect} onChange={onItemChange} />
        }
    </Input.Group>)
}


const TaskDetail = (props) => {

    const {
        projectId,
        taskId,
        dispatch,
        projectPermission,
        myInfo
    } = props

    const [isDetailTextEditFlag, setIsDetailTextEditFlag] = useState();
    const [isDetailTimeCostEditFlag, setIsDetailTimeCostEditFlag] = useState();
    const [isDetailItemIdEditFlag, setIsDetailItemIdEditFlag] = useState();
    const [taskDetail, setTaskDetail] = useState({})
    const [projectLogUpdate, setProjectLogUpdate] = useState(0)
    const [tabKey, setTabKey] = useState();
    const [permission, setPermission] = useState({
        edit: false,
        delete: false,
    })
    
    useEffect(() => {
        getDetail(projectId, taskId).then(({ data }) => {
            setTaskDetail(data)
        })
    }, [])

    useEffect(() => {
        if (taskDetail) {
            if (myInfo.id === taskDetail.userId) {
                setPermission({
                    ...permission,
                    edit: true,
                    delete: true,
                })
            }
        }
    }, [taskDetail])

    useEffect(() => {
        setPermission({
            ...projectPermission?.task
        })
    }, [projectPermission])



    if (!taskDetail || taskDetail.id !== taskId) {
        return <div className={styles.detailContainer}><Skeleton></Skeleton></div>
    }

    const updateName = (name) => {
        updateTask({
            name: name,
            oldData: {
                name: taskDetail.name
            }
        })
        taskDetail.name = name;
        setTaskDetail({ ...taskDetail })
    }

    const updateProjectUser = (userId, user) => {
        updateTask({
            userId: userId,
            payload: {
                userId: user.nickName
            },
            oldData: {
                userId: taskDetail.userId,
                payload: {
                    userId: taskDetail.user?.nickName
                }
            }
        })
        taskDetail.userId = userId;
        taskDetail.user = user;
        setTaskDetail({ ...taskDetail })
    }

    const updateProjectItem = (itemData) => {
        updateTask({
            projectItemId: itemData.projectItemId,
            projectItemType: itemData.projectItemType,
            payload: {
                projectItemId: itemData.projectItem.name
            },
            oldData: {
                projectItemId: taskDetail.projectItemId,
                projectItemType: taskDetail.projectItemType,
                payload: {
                    projectItemId: taskDetail.projectItem?.name
                }
            }
        })
        taskDetail.projectItemId = itemData.projectItemId;
        taskDetail.projectItemType = itemData.projectItemType;
        taskDetail.projectItem = itemData.projectItem
        setTaskDetail({ ...taskDetail })
    }

    const updateStatus = (status) => {
        updateTask({
            status: status,
            oldData: {
                status: taskDetail.status
            }
        })
        taskDetail.status = status;
        setTaskDetail({ ...taskDetail })
    }

    const updateActualStartDate = (dateTime) => {
        updateTask({
            actualStartDate: dateTime,
            oldData: {
                actualStartDate: taskDetail.actualStartDate
            }
        })
        taskDetail.actualStartDate = dateTime;
        setTaskDetail({ ...taskDetail })
    }

    const updateActualEndDate = (dateTime) => {
        updateTask({
            actualEndDate: dateTime,
            oldData: {
                actualEndDate: taskDetail.actualEndDate
            }
        })
        taskDetail.actualEndDate = dateTime;
        setTaskDetail({ ...taskDetail })
    }

    const updateActualDate = (actualDate) => {
        if (!checkRangeDateNotNull(actualDate)) {
            message.warning('请输入完成排期！')
            return;
        }
        updateTask({
            actualStartDate: actualDate[0],
            actualEndDate: actualDate[1],
            oldData: {
                actualStartDate: taskDetail.actualStartDate,
                actualEndDate: taskDetail.actualEndDate
            }
        })
        taskDetail.actualStartDate = actualDate[0];
        taskDetail.actualEndDate = actualDate[1];
        setTaskDetail({ ...taskDetail })
    }

    const updateTimeCost = (timeCost) => {
        if (timeCost === taskDetail.costTimeCnt) {
            return;
        }
        let updateTimeCost = timeCost === "" ? 0 : timeCost
        setIsDetailTimeCostEditFlag(false)
        updateTask({
            costTimeCnt: updateTimeCost,
            oldData: {
                actualEndDate: taskDetail.costTimeCnt
            }
        })
        taskDetail.costTimeCnt = updateTimeCost;
        setTaskDetail({ ...taskDetail })
    }

    const updateTaskContent = (content) => {
        const oldDataContent = {
            content: {
                text: taskDetail.content.text
            }
        };
        updateTask({
            content: content,
            oldData: oldDataContent
        })
        taskDetail.content = content;
        setTaskDetail({ ...taskDetail })
        setIsDetailTextEditFlag(false)
    }

    const updateTask = (values) => {
        update(taskDetail.projectId, taskId, values)
            .then(({ success }) => {
                if (success) {
                    message.success("保存成功")
                }
                if (tabKey === "log") {
                    setProjectLogUpdate(projectLogUpdate + 1)
                }
            })
    }

    const updatItemIsArchived = (isArchived) => {
        let title = ""
        if (isArchived === 1) {
            title = '确认归档，归档之后无法编辑，只能在归档列表中显示'
        } else {
            title = "确认撤销归档"
        }
        Modal.confirm({
            title: title,
            okText: '确认',
            cancelText: '取消',
            closable: true,
            onOk: (v) => {
                updateIsArchived(projectId, taskId, isArchived)
                    .then(result => {
                        if (result?.success) {
                            message.success("操作成功")
                            setTaskDetail({
                                ...taskDetail,
                                isArchived: isArchived
                            })
                        } else {
                            message.success(result?.errMsg)
                        }
                    })
                return Promise.resolve()
            }
        });
    }

    const deleteItem = () => {
        Modal.confirm({
            title: '确认删除，删除之后将无法恢复',
            okText: '确认',
            cancelText: '取消',
            closable: true,
            onOk: (v) => {
                deleteTask(projectId, taskId)
                    .then(result => {
                        if (result?.success) {
                            message.success("操作成功")
                            history.replace(`/projects/${projectId}/task`)
                        } else {
                            message.success(result?.errMsg)
                        }
                    })
                return Promise.resolve()
            }
        });
    }

    const renderDropDownAction = () => {
        let action = [];
        if (permission.edit) {
            action.push(taskDetail?.isArchived === 0 ?
                <TextButton key="archive" type="warning" onClick={() => {
                    updatItemIsArchived(1)
                }}>归档</TextButton> :
                <TextButton key="archive" type="warning" onClick={() => {
                    updatItemIsArchived(0)
                }}>撤销归档</TextButton>)
        }
        if (permission.delete) {
            action.push(<TextButton key="delete" type="danger" onClick={() => {
                deleteItem()
            }}>删除</TextButton>)
        }
        return action;
    }

    return <>
        <div className={styles.detailContainer}>
            <PageHeader
                onBack={() => history.go(-1)}
                title={<EditAble permission={permission}
                    value={taskDetail.name}
                    onSave={updateName}
                    type="input">
                    {taskDetail.name}
                </EditAble>}
                extra={[
                    <ActionDropdown
                        key="action"
                        placement="bottomLeft"
                        actions={renderDropDownAction()}
                    />
                ]}
            >
                <Descriptions column={3}>
                    <Descriptions.Item label='负责人' span={1}>
                        <EditAble permission={permission}
                            value={taskDetail.userId}
                            editComponentProps={{
                                projectId: taskDetail.projectId,
                                defaultOpen: true
                            }}
                            onSave={updateProjectUser}
                            type="userSelect">
                            <UserBrief user={taskDetail.user}></UserBrief>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label='状态' span={1}>
                        <EditAble permission={permission}
                            value={taskDetail.status}
                            editComponentProps={{
                                options: ArrayUtils.jsonToArray(PROJECT_TASK_STATUS).map(item => {
                                    return { value: item.key, label: item.value.name }
                                }),
                                defaultOpen: true
                            }}
                            onSave={updateStatus}
                            type="select">
                            <TaskStatus status={taskDetail.status}></TaskStatus>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="创建时间" span={1}>{taskDetail.createTime}</Descriptions.Item>
                    <Descriptions.Item label="关联项目" span={1}>
                        <EditAble permission={permission}
                            value={taskDetail.projectItem}
                            isEdit={isDetailItemIdEditFlag}
                            onEdit={() => {
                                setIsDetailItemIdEditFlag(true)
                            }}
                            onCancel={() => {
                                setIsDetailItemIdEditFlag(false)
                            }}
                            onSave={() => {
                                setIsDetailItemIdEditFlag(false)
                            }}
                            editComponent={
                                <TaskRelItemTypeSelect projectId={projectId}
                                    defaultItemType={taskDetail.projectItemType}
                                    defaultItemId={taskDetail.projectItemId}
                                    onSelect={(data) => {
                                        updateProjectItem(data)
                                        setIsDetailItemIdEditFlag(false)
                                    }}
                                    width="200px"
                                ></TaskRelItemTypeSelect>
                            }>
                            {taskDetail.projectItem && (<>{TASK_TYPE[taskDetail.projectItemType].name} - <ProjectItemLink
                                {...{
                                    projectId: projectId,
                                    name: taskDetail.projectItem.name,
                                    type: taskDetail.projectItemType,
                                    id: taskDetail.projectItem.id
                                }} /></>)}
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="消耗工时" span={2}>
                        <EditAble permission={permission}
                            value={taskDetail.costTimeCnt}
                            isEdit={isDetailTimeCostEditFlag}
                            onEdit={() => {
                                setIsDetailTimeCostEditFlag(true)
                            }}
                            onCancel={() => {
                                setIsDetailTimeCostEditFlag(false)
                            }}
                            onSave={() => {
                                setIsDetailTimeCostEditFlag(false)
                            }}
                            editComponent={
                                <Space>
                                    <NumberInput
                                        placeholder="请输入工时数"
                                        style={{ width: "100px" }}
                                        value={taskDetail.costTimeCnt}
                                        onSelect={(value) => {
                                            setIsDetailTimeCostEditFlag(false)
                                            updateTimeCost(value)
                                        }}
                                        onPressEnter={(value) => {
                                            setIsDetailTimeCostEditFlag(false)
                                            updateTimeCost(value)
                                        }}
                                        autoCompleteOptions={[{ value: '0.5' }, { value: '1' }, { value: '2' }, { value: '3' }, { value: '4' }, { value: '5' }]}
                                    ></NumberInput>
                                    {COST_TIME_UNIT[taskDetail.costTimeUnit].name}
                                </Space>
                            }>
                            {`${taskDetail.costTimeCnt} ${COST_TIME_UNIT[taskDetail.costTimeUnit].name}`}
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="排期" span={3}>
                        <EditAble permission={permission}
                            value={[taskDetail.actualStartDate, taskDetail.actualEndDate]}
                            editComponentProps={{
                                format: "YYYY-MM-DD",
                                defaultTime: moment('18:30:00', 'HH:mm:ss')
                            }}
                            onSave={updateActualDate}
                            type="rangePicker">
                            {`${formetDate(taskDetail.actualStartDate)} - ${formetDate(taskDetail.actualEndDate)}`}
                        </EditAble>
                        {taskDetail.planEndDate && <Tooltip placement="topLeft" title={`预计排期:${formetTime(taskDetail.planEndDate)} - ${formetDate(taskDetail.planEndDate)}`}><ClockCircleOutlined /></Tooltip>}
                    </Descriptions.Item>

                    <Descriptions.Item label="内容" span={3} />
                    <Descriptions.Item span={3} >
                        <EditAble permission={permission}
                            isEdit={isDetailTextEditFlag}
                            onEdit={() => {
                                setIsDetailTextEditFlag(true)
                            }}
                            width="100%"
                            value={taskDetail.content && taskDetail.content.raw}
                            onCancel={() => {
                                setIsDetailTextEditFlag(false)
                            }}
                            onSave={() => {
                                setIsDetailTextEditFlag(false)
                            }}
                            useCustomOperate={true}
                            editComponent={
                                <RichTextEdit
                                    size="small"
                                    onCancel={() => {
                                        setIsDetailTextEditFlag(false)
                                    }}
                                    onSave={updateTaskContent}
                                    value={taskDetail.content && taskDetail.content.raw}>
                                </RichTextEdit>
                            }>
                            <RichText
                                ellipsis
                                border
                                value={taskDetail.content && taskDetail.content.text}>
                            </RichText>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item span={1} />
                </Descriptions>
                <Tabs
                    tabBarGutter={-8}
                    activeKey={tabKey}
                    onChange={(atk) => {
                        setTabKey(atk);
                        setProjectLogUpdate(projectLogUpdate + 1)
                    }}
                >
                    <TabPane tab="评论" key="comment">
                        <ProjectComment projectId={projectId} bizId={taskDetail.id} bizType="task" />
                    </TabPane>
                    <TabPane tab="日志" key="log">
                        <ProjectItemLog
                            projectId={projectId}
                            itemId={taskDetail.id}
                            update={projectLogUpdate}
                            renderField={(value, fieldName, isDetail) => {
                                if (fieldName === "status") {
                                    return <TaskStatus status={value}></TaskStatus>
                                }
                                if (fieldName === "costTimeCnt") {
                                    return `${value || ''} ${COST_TIME_UNIT[taskDetail.costTimeUnit].name}`
                                }
                                if (Array.isArray(fieldName) && fieldName.indexOf("actualStartDate") >= 0) {
                                    return `${formetDate(value["actualStartDate"])} - ${formetDate(value["actualEndDate"])}`
                                }
                                if (Array.isArray(fieldName) && fieldName.indexOf("projectItemId") >= 0) {
                                    let payloadName = value?.payload && value?.payload[projectItemId]
                                    if (isDetail) {
                                        const linkProps = {
                                            projectId: projectId,
                                            name: payloadName,
                                            id: value.projectItemId,
                                            type: value.projectItemType
                                        }
                                        return <>
                                            {TASK_TYPE[value.projectItemType].name} - <ProjectItemLink {...linkProps} />
                                        </>
                                    }
                                    return `${TASK_TYPE[value.projectItemType].name} - ${payloadName}`;
                                }
                            }}
                            renderModalWidth={(fieldName) => {
                                if (Array.isArray(fieldName) && fieldName.indexOf("projectItemId") >= 0) {
                                    return '60%'
                                }
                            }}
                            renderFieldName={(fieldName) => {
                                if (fieldName === "costTimeCnt") {
                                    return `消耗工时`
                                }
                                if (Array.isArray(fieldName) && (fieldName[0] === "actualStartDate" || fieldName[1] === "actualStartDate")) {
                                    return "排期"
                                }
                                if (Array.isArray(fieldName) && fieldName.indexOf("projectItemId") >= 0) {
                                    return '关联开发项'
                                }
                            }}
                            itemType="task" />
                    </TabPane>
                </Tabs>
            </PageHeader>
        </div>
    </>
}
export { TaskRelItemTypeSelect };

export default connect(({ user }) => ({
    myInfo: user.myInfo
}))(TaskDetail);